from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from app.models import PayOrder, OrderExtInfo, OrderNotice
from app.common import enums
from app.common.enums import OrderStatus
from app.common.exceptions import GenericException
from app.common.enums.resp_enum import ErrTypes

import logging
logger = logging.getLogger(__name__)


#### 订单通知
def add_order_notice(db: Session, new_order: PayOrder, params: dict):
    #order_ext_info = db.query(OrderExtInfo).filter(OrderExtInfo.order_no == order_no).first()
    new_record = OrderNotice()
    new_record.order_no = new_order.order_no
    new_record.merc_order_no = new_order.merc_order_no
    new_record.notify_url = params.get('notify_url')
    new_record.status = 0
    new_record.fail_count = 0
    db.add(new_record)
    #db.commit()
    #return new_record

#### 订单扩展信息
def get_order_ext_info(db: Session, order_no: str):
    return db.query(OrderExtInfo).filter(OrderExtInfo.order_no == order_no).first()

def add_order_ext_info(db: Session, order_no: str):
    #order_ext_info = db.query(OrderExtInfo).filter(OrderExtInfo.order_no == order_no).first()
    new_record = OrderExtInfo()
    new_record.order_no = order_no
    #new_record.profit_status = 0
    new_record.is_data_accumulated = 'N'
    #new_record.is_profit_processed = 'N'
    db.add(new_record)
    #db.commit()
    #db.refresh(new_record)
    #return new_record

#### 订单表

def get_order_query_set_between_datetime(db: Session, start: datetime, end: datetime):
    query_set = db.query(PayOrder).filter(
        PayOrder.create_time >= start,
        PayOrder.create_time < end
    )
    return query_set


def get_orders(db: Session, skip: int = 0, limit: int = 10):
    return db.query(PayOrder).order_by(PayOrder.create_time.desc()).offset(skip).limit(limit).all()

def is_merc_order_exist(db: Session, merc_no: str, merc_order_no: str):
    res = db.query(PayOrder).filter(
        PayOrder.merc_no == merc_no,
        PayOrder.merc_order_no == merc_order_no
        ).first()
    if res:
        return True
    else:
        return False


def get_unfinished_status_orders(db: Session, limit: int = 20):
    return db.query(PayOrder).filter(
        PayOrder.is_profit_processed == 'N',
        PayOrder.status != OrderStatus.SUCCESS.value[0] or PayOrder.status != OrderStatus.FAIL.value[0] or PayOrder.status != OrderStatus.CANCEL.value[0]
    ).order_by(PayOrder.create_time.asc()).limit(limit).all()

def get_profit_not_processed_orders(db: Session, limit: int = 20):
    return db.query(PayOrder).filter(
        PayOrder.is_profit_processed == 'N',
        #PayOrder.status == OrderStatus.SUCCESS.value[0]
    ).order_by(PayOrder.create_time.asc()).limit(limit).all()


def get_order(db: Session, order_no: str):
    return db.query(PayOrder).filter(PayOrder.order_no == order_no).first()
